#!/bin/bash
set -e

ARCH="arm64"
CROSS_COMPILE="aarch64-target-linux-gnu-"
MACRO=ARM64_HI1711_ENABLED
KERNEL_PATH=$1
CONAN_CMAKE_SDK_ROOT=$2
DRIVERS_DIR="$(cd "$(dirname "$0")" && pwd)"
SCRIPT_DIR=$(
  cd "$DRIVERS_DIR" || exit 1
  cd "../kernel/" && pwd
)

export PATH=/opt/hcc_arm64le/bin:$PATH

for dir in "$DRIVERS_DIR"/*/; do
  if [ -d "$dir" ]; then
    # 进入每个同级文件夹，创建 tmp 目录
    (cd "$dir" && mkdir -p tmp
    cp *.c Makefile tmp/ 2>/dev/null || true
    # 如果有 .h 文件也复制
    if ls *.h >/dev/null 2>&1; then
        cp *.h tmp/
    fi
    
    # 复制 Module.symvers 文件
    if [ -f "$CONAN_CMAKE_SDK_ROOT/Module.symvers" ]; then
        cp $CONAN_CMAKE_SDK_ROOT/Module.symvers "$(pwd)/tmp/Module_sdk.symvers"
    else
        echo "Warning: $CONAN_CMAKE_SDK_ROOT/Module.symvers not found"
    fi
    
    cd tmp && make KBUILD_EXTRA_SYMBOLS="$(pwd)/Module_sdk.symvers" ARCH=$ARCH KERNEL_PATH=$KERNEL_PATH CROSS_COMPILE=$CROSS_COMPILE MACRO=$MACRO
    
    # 复制生成的 .ko 文件
    if ls *.ko >/dev/null 2>&1; then
        cp -r *.ko "$SCRIPT_DIR"
    else
        echo "Warning: No .ko files found in $dir"
    fi
    
    cd ..
    rm -rf tmp
    echo "$dir compile completed.")
  fi
done

echo "Drivers compile completed."

